const crypto = require('crypto');
const os = require('os');
const fs = require('fs');
const path = require('path');
const base32 = require('base32');

// ================== 核心算法修改 ==================

// 1. 硬件指纹生成 [ 生成机器指纹（基于硬件信息） ]
function generateHardwareId() {
    // 混合更稳定的硬件信息
    const components = [
        os.hostname(),                  // 主机名
        os.cpus()[0]?.model || '',      // CPU型号
        (os.networkInterfaces().eth0 || os.networkInterfaces().en0)?.mac || '', // MAC地址
        fs.statSync(__dirname).ino.toString()  // 安装目录inode
    ];

    return crypto.createHash('sha256')
        .update(components.join('|'))
        .digest('hex')
        .substring(0, 32); // 32位硬件指纹
}

// 2. 激活码生成算法（授权服务器端）;; 生成激活码（服务器端）
function generateLicense(email, hardwareId) {
    const secretKey = process.env.LICENSE_KEY || 'DEFAULT_SECRET_KEY'; // 从环境变量获取

    // 增加有效期和随机因子
    const rawData = [
        email.trim().toLowerCase(),     // 邮箱标准化
        hardwareId,
        Date.now().toString(),
        crypto.randomBytes(6).toString('hex'), // 更强的随机盐
        '1Y' // 有效期标识
    ].join('|');

    // AES-256-CBC加密增强
    const iv = crypto.randomBytes(16); // 动态IV提升安全性
    const cipher = crypto.createCipheriv(
        'aes-256-cbc',
        crypto.createHash('sha256').update(secretKey).digest(),
        iv
    );

    let encrypted = iv.toString('hex') + cipher.update(rawData, 'utf8', 'hex');
    encrypted += cipher.final('hex');

    // 优化输出格式：BASE32(IV +密文) 取前20字符
    const compressed = encrypted.substring(0, 40); // IV(16字节) + 密文(4字节)
    return base32.encode(Buffer.from(compressed, 'hex'))
        .replace(/=/g, '')
        .toUpperCase(); // 直接转为全大写，移除分组逻辑
        // .match(/.{1,5}/g)?.join('-') || ''; // 5字符分组
}

// 3. 客户端验证算法
function validateLicense(email, licenseKey, hardwareId) {
    try {
        const secretKey = process.env.LICENSE_KEY || 'DEFAULT_SECRET_KEY';

        // 解码并提取IV

        // 添加预处理（兼容用户手动输入的小写）
        const sanitizedKey = licenseKey.replace(/-/g, '').toUpperCase();

        // 解码时使用处理后的key
        const decoded = base32.decode(sanitizedKey);

        const encrypted = decoded.toString('hex');

        const iv = Buffer.from(encrypted.substring(0, 32), 'hex'); // 提取动态IV
        const cipherText = encrypted.substring(32, 72); // 剩余部分为密文

        // 解密
        const decipher = crypto.createDecipheriv(
            'aes-256-cbc',
            crypto.createHash('sha256').update(secretKey).digest(),
            iv
        );

        let decrypted = decipher.update(cipherText, 'hex', 'utf8');
        decrypted += decipher.final('utf8');

        // 解析并验证
        const parts = decrypted.split('|');
        return parts[0] === email.trim().toLowerCase() &&
            parts[1] === hardwareId &&
            parseInt(parts[2]) + 365 * 86400 * 1000 > Date.now(); // 1年有效期

    } catch (e) {
        console.error('License validation error:', e);
        return false;
    }
}

// ================== 激活状态管理 ==================

const getActivationFile = (app) => path.join(app.getPath('userData'), '.activation');

function saveActivationStatus(email, licenseKey, app) {
    const activationData = {
        email,
        licenseKey,
        hardwareId: generateHardwareId(),
        timestamp: Date.now(),
        signature: crypto.createHmac('sha256', 'SIGNING_SECRET')
            .update(`${email}|${licenseKey}`)
            .digest('hex')
    };

    fs.writeFileSync(getActivationFile(app),
        JSON.stringify(activationData),
        { encoding: 'utf8', mode: 0o600 }); // 设置文件权限
}

function checkActivation(app) {
    try {
        const data = JSON.parse(fs.readFileSync(getActivationFile(app), 'utf8'));

        // 三重验证：
        const isValid =
            crypto.timingSafeEqual(
                Buffer.from(data.signature),
                Buffer.from(crypto.createHmac('sha256', 'SIGNING_SECRET')
                    .update(`${data.email}|${data.licenseKey}`)
                    .digest('hex'))
            ) &&
            data.hardwareId === generateHardwareId() &&
            validateLicense(data.email, data.licenseKey, data.hardwareId);

        return isValid;
    } catch (e) {
        return false;
    }
}

module.exports = {
    generateHardwareId,
    generateLicense,
    validateLicense,
    saveActivationStatus,
    checkActivation
};